<template>
  <el-container style="height:100%; border: 1px solid #eee">
    <el-aside width="400px"  style="background-color: rgb(238, 241, 246)">
      <div style="height: 50px; margin-top: 10px; margin-left: 10px">
        <el-text style="font-size: 25px">组织信息</el-text>
      </div>
      <div>
        <el-scrollbar style="height: 500px; margin-top: 2px; margin-left: 2px">
          <el-tree
            :data="treeData"
            @node-click="handleNodeClick"
            :expand-on-click-node="false"
          >
            <span slot-scope="{ node, data }">
              <i :class="node.icon"></i>&nbsp;&nbsp;{{ node.label }}
            </span>
          </el-tree>
        </el-scrollbar>
      </div>
    </el-aside>

    <el-container>
      <el-header style="font-size: 12px">
        <div id="divSearch" ref="divSearch" style="margin-top: 30px">
          <el-form
            :inline="true"
            :model="Search"
            size="mini"
            class="demo-form-inline"
          >
            <el-form-item label="组织名称" prop="Search">
              <el-input v-model.trim="Search.organizename" placeholder="名称" />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="small"
                @click="getTableData"
                >查询</el-button
              >
              <el-button
                type="primary"
                icon="el-icon-circle-plus"
                size="small"
                @click="handeAdd"
                >新增</el-button
              >
              <el-button
                type="primary"
                icon="el-icon-thumb"
                size="small"
                @click="handeArrange"
                >整理组织</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-header>

      <el-main>
        <el-table
          :data="tabledata"
          style="width: 100%; margin-top: 10px"
          border
          @sort-change="sortChange"
          class="spheight"
          size="mini"
          height="90%"
        >
          

          <el-table-column align="center" label="组织编码" prop="organizeid" min-width=20%>
            <template slot-scope="scope">
              {{ scope.row.organizeid }}        
            </template>
          </el-table-column>

          <el-table-column align="center" label="组织名称" prop="organizename" min-width=20%>
            <template slot-scope="scope">
              {{ scope.row.organizename }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="上级编码" prop="forganizeid" min-width=20%>
            <template slot-scope="scope">
              {{ scope.row.forganizeid }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="具体名称" prop="longname" min-width=30%>
            <template slot-scope="scope">
              {{ scope.row.longname }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="节点" prop="NodesForganizeid" min-width=30%>
            <template slot-scope="scope">
              {{ scope.row.NodesForganizeid }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" min-width=30%>
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          layout="sizes, prev, pager, next,total"
          :page-size="Search.pageSize"
          :total="Search.total"
          @current-change="pageChange"
        />
        <el-form>
      <el-dialog :visible.sync="dialogVisible" width="1000px" top="20px">
        <el-tabs type="border-card">
          <el-tab-pane label="组织信息">
            <el-form :model="EditObj" :inline="true" label-width="120px" label-position="left">
              <el-form-item label="组织编码">
                <el-input v-model="EditObj.organizeid" placeholder=" 编号" :disabled="IsEdit"/>
              </el-form-item> 
              <br />
              <el-form-item label="组织名称">
                <el-input v-model="EditObj.organizename" placeholder="组织名称" />
              </el-form-item>
              <br />
              <el-form-item label="上级编码">
                <el-input v-model="EditObj.forganizeid" placeholder="上级编码" />
              </el-form-item>
              <br />
              <el-form-item label="具体名称">
                <el-input v-model="EditObj.longname" placeholder="具体名称" />
              </el-form-item>
              <br />
              <el-form-item label="是否计算">
                <el-select
                  v-model="EditObj.IsCalculation"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
               <br />
              <el-form-item label="是否生产部">
                <el-select
                  v-model="EditObj.isproc"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>

        <div style="text-align:right;">
          <el-button type="danger" @click="dialogVisible=false">取消</el-button>
          <el-button type="primary" @click="confirmData">提交</el-button>
        </div>
      </el-dialog>
    </el-form>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import path from "path";
import { deepClone } from "@/utils";
import elementIcons from "../icons/element-icons";
import { getDataList } from "@/api/datalist";
import {updateOrganizetionData,deletOrganizetionData,updateDepTree} from "@/api/System";

export default {
  data() {
    return {
      dialogVisible: false,
      dialogTableVisible: false,
      tableheight:(document.documentElement.clientHeight)*0.43,
      tabledata: [],
      EditObj:[],
      treeData: [],
      data: [],
      IsEdit:false,
      SearchTree: {
        // 查询条件
        total: 0, // 总记录数
        pageSize: 100000, // 一页显示的记录数
        page: 1, // /当前页码
        RNO: "005", // 表编号  根据Controller中对应的表编号
        jsWhere: "", // 自定义条件
      },
      Search: {
        // 查询条件
        total: 0, // 总记录数
        pageSize: 10, // 一页显示的记录数
        page: 1, // /当前页码
        RNO: "005", // 表编号  根据Controller中对应的表编号
        jsWhere: "", // 自定义条件
      },
      options: [
        {
          value: 0,
          label: "否",
        },
        {
          value: 1,
          label: "是",
        },
      ],
    };
  },
  created() {
    this.getDataList();
    this.actionGetCatalog();
    this.getTableData();
  },
  methods: {
    pageChange(page) {
      // 翻页
      this.Search.page = page;

      this.getTableData();
    },
    async getTableData() {
      // 获取列表数据，通用
      const res = await getDataList({ data: JSON.stringify(this.Search) });

      this.tabledata = res.data.Table; //将data 中的数据放到DataList中
      this.Search.total = res.data.Table1[0].RecordCount;
    },
    sortChange: function (column) {
      // column, prop, order,排序，通用
      this.Search.sort = column.prop + " " + column.order;

      this.getTableData();
    },
    async getDataList() {
      // 获取列表数据，通用
      const res = await getDataList({ data: JSON.stringify(this.SearchTree) });

      this.data = res.data.Table; //将data 中的数据放到DataList中
      this.SearchTree.total = res.data.Table[0].RecordCount;
      this.actionGetCatalog();
    },
    actionGetCatalog() {
      let data = this.data;
      for (let i = 0; i < data.length; i++) {
        //把"name"换成"label"
        data[i].label = data[i].organizename;
        delete data[i].organizename;
      }
      this.treeData = this.getJsonTree(data, {
        id: "organizeid",
        pid: "forganizeid",
        children: "children",
      });
      console.log(this.treeData);
    },
    handleNodeClick(data) {
      console.log(data);
    },
    //将json（一般从后台获取）转成jsonTree格式 参考文档：https://blog.csdn.net/unamattin/article/details/77152451
    getJsonTree(data, config) {
      let id = config.id || "id",
        pid = config.pid || "pid",
        children = config.children || "children";
      let idMap = [],
        jsonTree = [];
      data.forEach(function (v) {
        idMap[v[id]] = v;
      });
      data.forEach(function (v) {
        let parent = idMap[v[pid]];
        if (parent) {
          !parent[children] && (parent[children] = []);
          parent[children].push(v);
        } else {
          jsonTree.push(v);
        }
      });
      this.treeAddIcon(jsonTree); //循环遍历给tree加图标
      return jsonTree;
    },
    treeAddIcon(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].children) {
          data[i].icon = "iconfont icon-wenjianjia"; //icon来自阿里巴巴矢量图标库http://iconfont.cn
          this.treeAddIcon(data[i].children);
        } else {
          data[i].icon = "iconfont icon-wenjian";
        }
      }
    },  
     async handleDelete({ $index, row }) {
      //删除
      this.$confirm("确定删除该记录吗?", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        const result= await deletOrganizetionData({
          organizeid: JSON.stringify(row.organizeid),
        });
        this.tabledata.splice($index, 1);
        if (result.code === 20000) {
          this.dialogVisible = false;
          this.$notify({
            title: "Success",
            dangerouslyUseHTMLString: true,
            message: result.msg,
            type: "success",
          });
          this.getTableData();
        } else {
          this.$notify({
            title: "error",
            dangerouslyUseHTMLString: true,
            message: result.msg,
            type: "error",
          });
        }
      });
    },
    async handeAdd() {
      // 新建
      this.dialogVisible = true;
      const result = await updateOrganizetionData({
        EditObj: null,
        organizeid: "-1",
        IsPostBack: false,
      });
      this.EditObj = result.data.Table[0];
      this.IsEdit=false
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([]);
      }
    },
    async handleEdit(scope) {
      // 修改
      this.dialogVisible = true;
      this.checkStrictly = true;
      const result = await updateOrganizetionData({
        EditObj: null,
        organizeid: scope.row.organizeid,
        IsPostBack: false,
      });
      this.EditObj = result.data.Table[0];
      this.IsEdit=true
      this.$nextTick(() => {
        const routes = this.generateRoutes(this.EditObj.routes);
        this.$refs.tree.setCheckedNodes(this.generateArr(routes));
        this.checkStrictly = false;
      });
    },
    async confirmData() {
      // 提交数据，需要修改
      console.log(this.EditObj)
        const result = await updateOrganizetionData({
          organizeid: this.EditObj.organizeid,
          tabledata: JSON.stringify(this.EditObj),
          IsPostBack: true,
        });
        if (result.code === 20000) {
          this.$notify({
            title: "Success",
            dangerouslyUseHTMLString: true,
            message: result.msg,
            type: "success",
          });
          this.getTableData();
        } else {
          this.$notify({
            title: "error",
            dangerouslyUseHTMLString: true,
            message: result.msg,
            type: "error",
          });
        }
    },
    async handeArrange(){
      const result =await updateDepTree({});
      if (result.code === 20000) {
          this.$notify({
            title: "Success",
            dangerouslyUseHTMLString: true,
            message: result.msg,
            type: "success",
          });
        } else {
          this.$notify({
            title: "error",
            dangerouslyUseHTMLString: true,
            message: result.msg,
            type: "error",
          });
        }
    }
  },
};
</script>
<style>
.treeDemo .el-scrollbar__wrap {
  overflow-x: hidden;
}
.spheight td{
    height: 20px;
}
</style>